<template>
  <div class="common-layout">
      <el-card class="box-card operate-container" shadow="always">
        <el-row>
          <el-col :span="12" style="text-align: left">
            <el-link :underline="false" icon="Search">筛选搜索</el-link>
          </el-col>
          <el-col :span="12" style="text-align: right">
            <el-button type="primary" icon="Search" @click="queryPage">查 询</el-button>
            <el-button class="button">重置</el-button>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="24">
            <el-form :model="queryForm" :inline="true">
              <el-form-item label="账号/姓名:">
                <el-input v-model="queryForm.keyword"/>
              </el-form-item>
            </el-form>
          </el-col>
        </el-row>
      </el-card>
      <el-card class="box-card operate-container" shadow="always">
        <el-row>
          <el-col :span="12" style="text-align: left">
            <el-link :underline="false" icon="Document">数据列表</el-link>
          </el-col>
          <el-col :span="12" style="text-align: right">
            <el-button type="primary" icon="Plus" @click="addAdmin">新 增</el-button>
          </el-col>
        </el-row>
      </el-card>
      <div class="table-container">
        <el-table :data="tableData" border style="width: 100%">
          <el-table-column prop="id" label="编号" align="center"/>
          <el-table-column prop="username" label="账号" align="center"/>
          <el-table-column prop="nickName" label="姓名" align="center"/>
          <el-table-column prop="email" label="邮箱" align="center"/>
          <el-table-column prop="createTime" label="添加时间" align="center">
            <template #default="scope">
              {{ formateDate(scope.row.createTime) }}
            </template>
          </el-table-column>
          <el-table-column prop="loginTime" label="最后登录" align="center">
            <template #default="scope">
              {{ formateDate(scope.row.loginTime) }}
            </template>
          </el-table-column>
          <el-table-column prop="status" label="是否启用" align="center">
            <template #default="scope">
              <el-switch v-model="scope.row.status" :active-value="1" :inactive-value="0"/>
            </template>

          </el-table-column>
          <el-table-column label="操作" width="220" align="center">
            <template #default="scope">
              <el-button :text="true" size="small" type="primary" @click="allocRole(scope.row.id)">分配角色</el-button>
              <el-button :text="true" size="small" type="primary" @click="editAdmin(scope.row)">编辑</el-button>
              <el-button :text="true" size="small" type="warning" @click="deleteAdmin(scope.row)">删除</el-button>
            </template>
          </el-table-column>
        </el-table>
      </div>
      <div class="pagination-container">
        <el-pagination
            background
            v-model:currentPage="queryForm.pageNum"
            v-model:page-size="queryForm.pageSize"
            :page-sizes="pageSizes"
            layout="total, sizes, prev, pager, next, jumper"
            :total="totalCount"
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
        />
      </div>
  </div>
  <EditAdmin :visible="visible" :isAdd="isAdd" @close="closeDialog" :form="rowData"/>
  <EditRole :visible="roleVisible" @close="closeRoleDialog" :form="roleData"/>
</template>

<script setup lang="ts">
import {reactive, toRefs, ref} from 'vue'
import {getAdminListApi, getAdminRoleApi, getAdminInfoByIdApi, deleteAdminInfoByIdApi} from '../../../request/api/user'
import {getRolesApi} from '../../../request/api/role'
import EditAdmin from './component/EditAdmin.vue'
import EditRole from './component/EditRole.vue'
import {ElMessage, ElMessageBox} from 'element-plus'

const state = reactive<{
  tableData: {}[],
  visible: boolean,
  isAdd: boolean,
  rowData: AdminObjItf,
  roleVisible: boolean,
  roleData: AdminRoleFormData,
  totalCount: number,
  pageSizes: number[],
  queryForm: AdminQueryPageParams
}>({
  tableData: [],
  visible: false,
  isAdd: true,
  roleVisible: false,
  rowData: {},
  roleData: {
    roleLists: [],
    userRoles: [],
    adminId: 0
  },
  totalCount: 100,
  pageSizes: [5, 10, 15, 20],
  queryForm: {
    keyword: '',
    pageNum: 1,
    pageSize: 5
  }
})

const {
  tableData,
  visible,
  isAdd,
  rowData,
  roleVisible,
  roleData,
  totalCount,
  pageSizes,
  queryForm
} = toRefs(state)

const queryPage = () => {
  getAdminListApi(queryForm.value).then(res => {
    if (res.code === 200) {
      tableData.value = res.data.list
      totalCount.value = res.data.total
    }
  })
}

queryPage();

// 点击新增用户按钮
const addAdmin = () => {
  isAdd.value = true
  visible.value = true
}

// 点击编辑用户按钮
const editAdmin = (row: AdminObjItf) => {
  // 获取用户信息
  getAdminInfoByIdApi(row.id as number).then(res => {
    if (res.code === 200) {
      rowData.value = res.data
      isAdd.value = false
      visible.value = true
    }
  })

}

// 删除用户按钮
const deleteAdmin = (row: AdminObjItf) => {
  // 弹框
  ElMessageBox.confirm(
      `是否确定要删除用户：${row.username}?`,
      '警告',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      }
  ).then(() => {
    deleteAdminInfoByIdApi(row.id as number).then(res => {
      if (res.code === 200) {
        queryPage()
      }
    })
  }).catch(() => {
    console.log("取消操作")
  })
}

// 获取所有角色
getRolesApi().then(res => {
  console.log(res)
  if (res.code === 200) {
    roleData.value.roleLists = res.data
  }
})

// 点击分配角色按钮
const allocRole = (data: number) => {
  // 获取用户的角色
  getAdminRoleApi(data).then(res => {
    roleData.value.userRoles = res.data
    roleData.value.adminId = data
    roleVisible.value = true
  })

}

// 隐藏弹框
const closeDialog = (data?: 'reload') => {
  visible.value = false;
  rowData.value = {};
  if (data === 'reload') {
    // 更新表格数据
    queryPage();
  }
}

// 隐藏弹框
const closeRoleDialog = () => {
  roleVisible.value = false;
}

// 修改每页条数
const handleSizeChange = (data: number) => {
  queryForm.value.pageSize = data
  queryPage()
}

// 修改当前页
const handleCurrentChange = (data: number) => {
  queryForm.value.pageNum = data
  queryPage()
}

// 格式化时间
const formateDate = (data?: string) => {
  if (!data) return ''
  let date = new Date(data);
  let year = date.getFullYear();
  let month = addZero(date.getMonth() + 1);
  let day = addZero(date.getDay());
  let hours = addZero(date.getHours());
  let minutes = addZero(date.getMinutes());
  let seconds = addZero(date.getSeconds());
  return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`
}

const addZero = (num: number) => {
  return num > 9 ? num : `0${num}`
}

</script>

<style lang="less" scoped>

</style>
